<template>
  <div class="app-container">
    <div class="page-header">
      <h2 class="page-title">新建模型部署</h2>
    </div>

    <el-form
      ref="taskForm"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="task-form"
    >
      <!-- 基本任务配置 -->
      <div class="form-section">
        <h3 class="section-title">基本任务配置</h3>

        <!-- 服务名称 -->
        <el-form-item label="服务名称" prop="serviceName">
          <el-input v-model="form.serviceName" placeholder="请输入服务名称" />
        </el-form-item>

        <!-- 服务编码 -->
        <el-form-item label="服务编码" prop="serviceCode">
          <el-input v-model="form.serviceCode" placeholder="请输入服务编码" />
        </el-form-item>

        <!-- 报码模块 -->
        <el-form-item label="报码模块" prop="reportCode">
          <el-input v-model="form.reportCode" placeholder="请输入报码模块" />
        </el-form-item>

        <!-- 任务选择 -->
        <el-form-item label="任务选择" prop="taskId">
          <el-select
            v-model="form.taskId"
            placeholder="请选择任务"
            style="width: 100%"
          >
            <el-option
              v-for="item in taskOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 服务器选择 -->
        <el-form-item label="服务器选择" prop="serviceHost">
          <el-select
            v-model="form.serviceHost"
            placeholder="请选择服务器"
            style="width: 100%"
          >
            <el-option
              v-for="item in serverOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 接口方法 -->
        <el-form-item label="接口方法" prop="serviceApiMethod">
          <el-select
            v-model="form.serviceApiMethod"
            placeholder="请选择接口方法"
            style="width: 100%"
          >
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-form-item>

        <!-- 接口路径 -->
        <el-form-item label="接口路径" prop="serviceApiPath">
          <el-input
            v-model="form.serviceApiPath"
            placeholder="请输入接口路径"
          />
        </el-form-item>

        <!-- 服务描述 -->
        <el-form-item label="服务描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入服务描述"
          />
        </el-form-item>
      </div>

      <!-- 数据配置 -->
      <div class="form-section">
        <h3 class="section-title">数据配置</h3>

        <!-- 环境选择 -->
        <el-form-item label="环境选择" prop="envSelection">
          <el-select
            v-model="form.envSelection"
            placeholder="请选择环境"
            style="width: 100%"
          >
            <el-option label="生产环境" value="production" />
            <el-option label="测试环境" value="testing" />
          </el-select>
        </el-form-item>

        <!-- API方法 -->
        <el-form-item label="API方法" prop="apiMethod">
          <el-select
            v-model="form.apiMethod"
            placeholder="请选择API方法"
            style="width: 100%"
          >
            <el-option
              v-for="item in apiMethodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- API Host -->
        <el-form-item label="API Host" prop="apiHost">
          <el-input v-model="form.apiHost" placeholder="请输入API Host" />
        </el-form-item>

        <!-- API路径 -->
        <el-form-item label="API路径" prop="apiDataPath">
          <el-input v-model="form.apiDataPath" placeholder="请输入API路径" />
        </el-form-item>

        <!-- 请求类 -->
        <el-form-item label="请求类" prop="dataRequestClass">
          <el-input
            v-model="form.dataRequestClass"
            placeholder="请输入请求类"
          />
        </el-form-item>

        <!-- 响应类 -->
        <el-form-item label="响应类" prop="dataResponseClass">
          <el-input
            v-model="form.dataResponseClass"
            placeholder="请输入响应类"
          />
        </el-form-item>
      </div>

      <!-- 表单操作按钮 -->
      <div class="form-actions">
        <el-button type="primary" @click="submitForm">创建部署</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup name="DeploymentCreate">
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElLoading } from "element-plus";
import { buildBentoPackage, getTrainingTaskList } from "@/api/deploy";

const router = useRouter();
const { proxy } = getCurrentInstance();
const taskForm = ref(null);

// 表单数据
const form = reactive({
  serviceName: "",
  serviceCode: "",
  reportCode: "",
  taskId: "",
  serviceHost: "",
  serviceApiMethod: "",
  serviceApiPath: "",
  description: "",
  envSelection: "",
  apiMethod: "",
  apiHost: "",
  apiDataPath: "",
  dataRequestClass: "",
  dataResponseClass: "",
});

// 表单校验规则
const rules = {
  serviceName: [{ required: true, message: "请输入服务名称", trigger: "blur" }],
  serviceCode: [{ required: true, message: "请输入服务编码", trigger: "blur" }],
  reportCode: [{ required: true, message: "请输入报码模块", trigger: "blur" }],
  taskId: [{ required: true, message: "请选择任务", trigger: "change" }],
  serviceHost: [{ required: true, message: "请选择服务器", trigger: "change" }],
  serviceApiMethod: [
    { required: true, message: "请选择接口方法", trigger: "change" },
  ],
  serviceApiPath: [
    { required: true, message: "请输入接口路径", trigger: "blur" },
  ],
  envSelection: [{ required: true, message: "请选择环境", trigger: "change" }],
  apiHost: [{ required: true, message: "请输入API Host", trigger: "blur" }],
  apiDataPath: [{ required: true, message: "请输入API路径", trigger: "blur" }],
  dataRequestClass: [
    { required: true, message: "请输入请求类", trigger: "blur" },
  ],
  dataResponseClass: [
    { required: true, message: "请输入响应类", trigger: "blur" },
  ],
};

const taskOptions = ref([]);
const serverOptions = ref([{ value: "127.0.0.1", label: "127.0.0.1" }]);

const apiMethodOptions = ref([
  { value: "GET", label: "GET" },
  { value: "POST", label: "POST" },
  { value: "PUT", label: "PUT" },
  { value: "DELETE", label: "DELETE" },
]);

function handleServerCreate(value) {
  const newServer = {
    value: value,
    label: value,
  };
  serverOptions.value.push(newServer);
  form.serviceHost = newServer.value;
}

/** 获取任务列表 */
async function getTaskOptions() {
  try {
    const response = await getTrainingTaskList();
    // BentoML 接口返回格式：{ tasks: [...], total: ... } 或直接是 tasks 数组
    const tasks = response.tasks || response.data || response || [];
    taskOptions.value = tasks.map((task) => ({
      value: task.task_id,
      label: task.task_name || task.model_name || task.task_id,
    }));
  } catch (error) {
    console.error("获取任务列表失败:", error);
    ElMessage.error("获取任务列表失败");
  }
}

async function submitForm() {
  try {
    const valid = await proxy.$refs["taskForm"].validate();
    if (!valid) return;

    const loading = ElLoading.service({
      lock: true,
      text: "正在创建部署...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    // 准备 ServiceForm 数据（对外 API 配置）
    const serviceInfo = {
      service_name: form.serviceName,
      service_code: form.serviceCode,
      report_code: form.reportCode,
      task_id: form.taskId,
      service_host: form.serviceHost || null,
      api_method: form.serviceApiMethod,
      api_path: form.serviceApiPath,
      api_request_class: form.dataRequestClass || "",
      api_response_class: form.dataResponseClass || "",
      description: form.description,
    };

    // 准备 APISpecsDefined 数据（模型计算依赖的外部数据接口配置）
    const apiInfo = {
      api_method: form.apiMethod || null,
      api_host: form.apiHost || null,
      api_path: form.apiDataPath || null,
      api_headers: { "Content-Type": "application/json" },
      api_params: { dataset: "test_data" },
      request_class: form.dataRequestClass || null,
      response_class: form.dataResponseClass || null,
    };

    // 构建 BentoBuildRequest
    const requestData = {
      service_info: serviceInfo,
      api_info: apiInfo,
      // 可选字段
      bento_name: null, // 默认使用 service_name
      model_tag: null, // 默认使用 service_info.task_id
      python_packages: null,
      requirements_text: null,
      docker_base_image: null,
      python_version: null,
      cuda_version: null,
      description: form.description || null,
    };

    await buildBentoPackage(requestData);
    loading.close();
    ElMessage.success("创建部署成功");
    router.push("/model/deployment");
  } catch (error) {
    console.error("创建部署失败:", error);
    ElMessage.error("创建部署失败: " + (error.message || "未知错误"));
  }
}

function cancel() {
  router.push("/model/deployment");
}

// 初始化数据
onMounted(async () => {
  try {
    await getTaskOptions();
  } catch (error) {
    console.error("初始化数据失败:", error);
    ElMessage.error("初始化数据失败");
  }
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.task-form {
  max-width: 800px;
  margin: 0 auto;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}
</style>
